<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="innerCode">
        <el-input
          v-model="queryParams.innerCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    
    <el-table v-loading="loading" :data="vmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-talbe-column label="序号" type="index" width="50" align="center" prop="id" />
      <el-table-column label="设备编号" align="center" prop="innerCode" />
      <el-table-column label="设备型号" align="center" prop="vmTypeId"  >
      <template #default="scope">
        <div v-for="item in vmTypeList" :item="item.id">
            <span v-if="item.id==scope.row.vmTypeId">{{item.name}}</span>
        </div>
      </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="addr" show-overflow-tooltip />
      <el-table-column label="运营状态" align="center" prop="vmStatus" >
        <template #default="scope">
          <dict-tag :options="vm_status" :value="scope.row.vmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="运行状态" align="center" prop="runningStatus" >
        <template #default="scope">
            <!-- <dict-tag :options="runningStatus" :value="scope.row.runningStatus.status"/> -->
            {{ scope.row.runningStatus?.status ? '正常' : '异常' }}
         </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  @click="getVmInfo(scope.row)" v-hasPermi="['manage:vm:query']">查看详情</el-button>    
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog  title="设备详情" v-model="getVmInfoOpen" width="800px" append-to-body v-draggable>
      <el-form ref="VmStatusRef" :model="form" :rules="rules" label-width="80px">
      <div class="dialog-content">
            <!-- 销售信息 -->
            <div class="info-row">
              <span>销售量：{{statisticsData.salesCount}}</span>
              <span>销售额：{{statisticsData.salesAmount}}</span>
              <span>补货次数：{{TaskCount.supplyCount}}次</span>
              <span>维修次数：{{TaskCount.repairCount}}次</span>
            </div>

            <!-- 商品销量表格 -->
            <div class="table-title">商品销量（月）</div>
            <el-table :data="OrderList" border style="width: 100%">
              <el-table-column label="商品名称" align="center" >
                <template #default="scope">
                  {{ scope.row.skuName }}
                </template>
              </el-table-column>
              <el-table-column label="销售量" align="center" >
                <template #default="scope">
                  {{scope.row.salesCount}}
                </template>
              </el-table-column>
            </el-table>

            <!-- 调整货道按钮 -->
            <div class="adjust-btn">
              <el-link type="primary" @click="handleAdjustChannel">调整货道</el-link>
            </div>
          </div>
      </el-form>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <el-button @click="getVmInfoOpen = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
    <!-- 货道调整对话框 -->
    <ChannelDialog :goodVisible="goodVisible" :goodData="goodData" @handleCloseGood="handleCloseGood"></ChannelDialog>
  </div>

</template>

<script setup name="Vm">
import { listVm, getVm, delVm, addVm, updateVm } from "@/api/manage/vm";
import { listVmType } from "@/api/manage/vmType";
import {getOrderInfo} from "@/api/manage/order";
import {getTaskCount} from "@/api/manage/task";
import { listPartner } from "@/api/manage/partner";
import {listNode} from "@/api/manage/node";
import { listRegion} from "@/api/manage/region";
import { loadAllParams } from "../../../api/page";
const { proxy } = getCurrentInstance();
const { vm_status } = proxy.useDict('vm_status');
import ChannelDialog from "../vm/components/ChannelDialog.vue";


const vmList = ref([]);
const open = ref(false);
const modifyOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const vmTypeList = ref([]);
const partnerList = ref([]);
const nodeList = ref([]);
const regionList = ref([]);
const OrderList = ref([]);
const statisticsData= ref({
    salesCount: 0, // 销售量
    salesAmount: 0 // 销售额
});
const TaskCount= ref({
    supplyCount: 0, // 补货次数
    repairCount: 0, // 维修次数
});
const runningStatus = [
  { dictValue: true, label: '正常' },
  { dictValue: false, label: '异常' }
];
const getVmInfoOpen = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    innerCode: null,
    nodeId: null,
    businessType: null,
    regionId: null,
    partnerId: null,
    vmTypeId: null,
    vmStatus: null,
    runningStatus: null,
  },
  rules: {
    nodeId: [
      { required: true, message: "点位Id不能为空", trigger: "blur" }
    ],
    vmTypeId: [
      { required: true, message: "设备型号不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
onBeforeMount(() => {
  init();
});
function init() { 
    listVmType(loadAllParams).then(response => {
      vmTypeList.value = response.rows;
    });
    listPartner(loadAllParams).then(response => {
      partnerList.value = response.rows;
    });
    listNode(loadAllParams).then(response => {
      nodeList.value=response.rows;
    });
    listRegion(loadAllParams).then(response => {
      regionList.value = response.rows;
    });
}
//查看详情
function getVmInfo(row) {
  statisticsData.value={salesCount:0,salesAmount:0}; 
  getVmInfoOpen.value=true;
  getVm(row.id).then(response => {
    form.value = response.data;
  });
  const innerCode = row.innerCode;
  getOrderInfo(innerCode,2).then(response => {
    OrderList.value = response.rows;

    if (response.rows.length > 0) {
      const stats = response.rows.reduce((acc, row) => {
        acc.salesCount += parseInt(row.salesCount) || 0;
        acc.salesAmount += parseInt(row.salesAmount) || 0;
        return acc;
      }, { 
        salesCount: 0, 
        salesAmount: 0, 
      });
      // 更新 statisticsData
      statisticsData.value = stats;
      console.log(stats);
    }
  });
  getTaskCount(innerCode).then(response => {
     TaskCount.value= response.data;
  });
}
const goodVisible = ref(false); //货道弹层显示隐藏
const goodData = ref({}); //货道信息用来拿取 vmTypeId和innerCode
//调整货道
function handleAdjustChannel(){
  goodVisible.value = true;
  goodData.value = form.value;
}
/** 查询设备管理列表 */
function getList() {
  loading.value = true;
  listVm(queryParams.value).then(response => {
    vmList.value = response.rows;
    //向vmList插入运行状态
    vmList.value.forEach(item => {
      try {
        item.runningStatus = JSON.parse(item.runningStatus);
      } catch (e) {
        item.runningStatus = { statusCode: '', status: false }; // 异常时默认值
      }
    });
    console.log(vmList.value);
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  modifyOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    innerCode: null,
    channelMaxCapacity: null,
    nodeId: null,
    addr: null,
    lastSupplyTime: null,
    businessType: null,
    regionId: null,
    partnerId: null,
    vmTypeId: null,
    vmStatus: null,
    runningStatus: null,
    longitudes: null,
    latitude: null,
    clientId: null,
    policyId: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("vmRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getVm(_id).then(response => {
    form.value = response.data;
    modifyOpen.value = true;
    title.value = "修改设备管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["vmRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateVm(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          modifyOpen.value = false;
          getList();
        });
      } else {
        addVm(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备管理编号为"' + _ids + '"的数据项？').then(function() {
    return delVm(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/vm/export', {
    ...queryParams.value
  }, `vm_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped>
.dialog-content {
  padding: 20px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 14px;
}

.table-title {
  margin: 10px 0 10px;
  font-weight: bold;
}

.adjust-btn {
  text-align: right;
  margin: 20px 0;
}

.el-link {
  color: #409eff;
  cursor: pointer;
}
</style>
